#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Text;

namespace OshHost.Web
{
	public class HttpHeaders : NameValueCollection
	{
		public static string HeaderContentLength = "Content-Length";
		public static string HeaderContentType = "Content-Type";
		public static string HeaderExpires = "Expires";
		public static string HeaderLastModified = "Last-Modified";
		public static string HeaderUserAgent = "User-Agent";

		public HttpHeaders()
		{
		}

		public static HttpHeaders Parse(string headers)
		{
			HttpHeaders headerCollection = new HttpHeaders();
			string[] headerList = headers.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
			foreach(string header in headerList)
			{
				int colonIndex = header.IndexOf(':');
				if(colonIndex > 0 && colonIndex + 1 < header.Length)
					headerCollection.Add(header.Substring(0, colonIndex),
						header.Substring(colonIndex + 1).Trim());
				else
					Debug.Assert(false);
			}
			return headerCollection;
		}

		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < this.Count; i++)
			{
				string key = this.Keys[i];
				string[] values = this.GetValues(i);
				foreach(string value in values)
				{
					sb.Append(key);
					sb.Append(": ");
					sb.Append(value);
					sb.Append("\r\n");
				}
			}
			return sb.ToString();
		}

		public bool GetDateTime(string headerName, out long fileTime)
		{
			fileTime = 0;
			DateTime fileDateTime;
			if(!GetDateTime(headerName, out fileDateTime))
				return false;

			try
			{
				fileTime = fileDateTime.ToFileTimeUtc();
				return true;
			}
			catch(ArgumentOutOfRangeException) {}
			return false;
		}

		public bool GetDateTime(string headerName, out DateTime dateTime)
		{
			dateTime = DateTime.MinValue;
			string header = this[headerName];
			if(string.IsNullOrEmpty(header))
				return false;

			return DateTime.TryParseExact(header, "R",
				CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTime);
		}
	}
}
